package pl.edu.agh.iosr.gamblingzone.adminpanel.action;

import java.util.Iterator;
import java.util.List;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.richfaces.model.ScrollableTableDataModel.SimpleRowKey;
import org.richfaces.model.selection.SimpleSelection;

import pl.edu.agh.iosr.gamblingzone.model.Discipline;
import pl.edu.agh.iosr.gamblingzone.model.Group;
import pl.edu.agh.iosr.gamblingzone.utils.DAOFactory;
import pl.edu.agh.iosr.gamblingzone.dao.DisciplineDAO;
import pl.edu.agh.iosr.gamblingzone.dao.GroupDAO;

@Stateful
@Scope(ScopeType.SESSION)
@Name("groupsManage")
public class GroupManageAction implements GroupManage {

	/** The dao. */
	@In(required=true)
	DAOFactory dao;

	private List<Group> all;
	private GroupDAO groupDAO;
	private DisciplineDAO disciplineDAO;
	private SimpleSelection selection;
	private Discipline selectedDiscipline;
	private String newGroupName = "";
	private String newGroupDesc = "";

	@Create
	public void init() {
		groupDAO = dao.getGroupDAO();
		disciplineDAO = dao.getDisciplineDAO();
		newGroupName = "";
		newGroupDesc = "";
	}
	
	@Remove
	public void remove() {
		// NOTHING TO DO
	}
	
	public SimpleSelection getSelection() {
		return selection;
	}

	public void setSelection(SimpleSelection selection) {
		this.selection = selection;
	}

	public void takeSelection() {
		if (selection != null) {
			Iterator<SimpleRowKey> iterator = getSelection().getKeys();
			if (iterator.hasNext()) {
				SimpleRowKey rowKey = iterator.next();
				setSelectedDiscipline(disciplineDAO.findAll().get(rowKey.intValue()));
			}
			Group group = new Group();
			group.setName(getNewGroupName());
			group.setDescription(getNewGroupDesc());
			//groupDAO.makePersistent(group);
			getSelectedDiscipline().addGroup(group);
		}
	}

	public void removeGroup(Group g) {
		groupDAO.makeTransient(g);
	}

	public Discipline getSelectedDiscipline() {
		return selectedDiscipline;
	}

	public void setSelectedDiscipline(Discipline selectedDiscipline) {
		this.selectedDiscipline = selectedDiscipline;
	}

	public String getNewGroupName() {
		return newGroupName;
	}

	public void setNewGroupName(String newGroupName) {
		this.newGroupName = newGroupName;
	}

	public String getNewGroupDesc() {
		return newGroupDesc;
	}

	public void setNewGroupDesc(String newGroupDesc) {
		this.newGroupDesc = newGroupDesc;
	}

	public List<Group> getAll() {
		all = groupDAO.findAll();
		return all;
	}

}
